var defaultPage = Public.getDefaultPage();
var config = defaultPage.CONFIG;
var system = defaultPage.SYSTEM;
var api = frameElement.api, W = api.opener;
var _height = $(parent).height()-325,_width = $(parent).width()-32;
var project={};

var handle = {
	formatPosition:function(val, opt, row){
		return row.spf_position=="0"?"表头":"表尾";
	},
	formatFieldShow:function(val, opt, row){
		var html = '';
		html += '<input type="checkbox" '+(row.spf_show=="1"?"checked":"")+' onclick="javascript:$(this).next().val(this.checked?1:0);"/>';
		html += '<input type="hidden" id="fieldShow_'+row.spf_id+'" value="'+row.spf_show+'"/>';
		return html;
	},
	formatDataShow:function(val, opt, row){
		var html = '';
		html += '<input type="checkbox" '+(row.spd_show=="1"?"checked":"")+' onclick="javascript:$(this).next().val(this.checked?1:0);"/>';
		html += '<input type="hidden" id="dataShow_'+row.spd_id+'" value="'+row.spd_show+'"/>';
		return html;
	},
	formatDataAlign:function(val, opt, row){
		if ($.trim(row.spd_align) == '') {
			return '';
		}
		var html = '';
		html += "<input onclick='javascript:$(this).siblings(\"input:last\").val($(this).val());' type='radio' name='radio"+row.spd_id+"' "+(row.spd_align=="0"?"checked":"")+" value='0'/>左";
		html += "<input onclick='javascript:$(this).siblings(\"input:last\").val($(this).val());' type='radio' name='radio"+row.spd_id+"' "+(row.spd_align=="1"?"checked":"")+" value='1'/>中";
		html += "<input onclick='javascript:$(this).siblings(\"input:last\").val($(this).val());' type='radio' name='radio"+row.spd_id+"' "+(row.spd_align=="2"?"checked":"")+" value='2'/>右";
		html += '<input type="hidden" id="dataAlign_'+row.spd_id+'" value="'+row.spd_align+'"/>';
		return html;
	},
	buildPrint:function(){
		var print = {};
		print.sp_id = $("#sp_id").val();
		print.sp_name = $("#sp_name").val();
		print.sp_type = $('#selectType option:selected').val();
		var sp_remark = "";
		try {
			var editor = UE.getEditor('sp_remark');
			if (editor != null && editor != undefined) {
				editor.sync();
				var content = editor.getContent();
				content = content.replace("\u2028", "\\u2028").replace(
						"\u2029", "\\u2029");
				content = content.replace(" ", "&nbsp;");
				sp_remark = content;
			}
		} catch (e) {
		}
		print.sp_remark = sp_remark;
		return print;
	},
	buildPrintSet:function(){
		var printSets = [];
		printSets.push({sps_code:'page_width',sps_name:$('#page_width').val()});
		printSets.push({sps_code:'page_height',sps_name:$('#page_height').val()});
		printSets.push({sps_code:'page_left',sps_name:$('#page_left').val()});
		printSets.push({sps_code:'page_top',sps_name:$('#page_top').val()});
		printSets.push({sps_code:'page_right',sps_name:$('#page_right').val()});
		printSets.push({sps_code:'page_bottom',sps_name:$('#page_bottom').val()});
		printSets.push({sps_code:'page_title',sps_name:$('#page_title').val()});
		printSets.push({sps_code:'title_font',sps_name:$('#title_font').val()});
		printSets.push({sps_code:'title_height',sps_name:$('#title_height').val()});
		printSets.push({sps_code:'title_size',sps_name:$('#title_size').val()});
		printSets.push({sps_code:'head_font',sps_name:$('#head_font').val()});
		printSets.push({sps_code:'head_size',sps_name:$('#head_size').val()});
		printSets.push({sps_code:'page_direction',sps_name:$('#page_direction').val()});
		printSets.push({sps_code:'table_font',sps_name:$('#table_font').val()});
		printSets.push({sps_code:'table_size',sps_name:$('#table_size').val()});
		printSets.push({sps_code:'table_top',sps_name:$('#table_top').val()});
		printSets.push({sps_code:'table_bold',sps_name:$('#table_bold').is(':checked')?"1":"0"});
		printSets.push({sps_code:'table_subtotal',sps_name:$('#table_subtotal').is(':checked')?"1":"0"});
		printSets.push({sps_code:'table_total',sps_name:$('#table_total').is(':checked')?"1":"0"});
		printSets.push({sps_code:'table_headheight',sps_name:$('#table_headheight').val()});
		printSets.push({sps_code:'end_endshow',sps_name:$('#end_endshow').val()});
		printSets.push({sps_code:'table_dataheight',sps_name:$('#table_dataheight').val()});
		printSets.push({sps_code:'head_height',sps_name:$('#head_height').val()});
		return printSets;
	},
	buildPrintField:function(){
		var printFields = [];
		var ids = $("#grid").jqGrid('getDataIDs');
		if(ids == "" || ids.length == 0){
			return printFields;
		}
		var field = null;
		for(var i=0;i < ids.length;i++){
			var rowData = $("#grid").jqGrid("getRowData", ids[i]);
			field = {};
			field.spf_id = rowData.spf_id;
			field.spf_code = rowData.spf_code;
			field.spf_name = rowData.spf_name;
			field.spf_namecustom = rowData.spf_namecustom;
			field.spf_line = rowData.spf_line;
			field.spf_row = rowData.spf_row;
			field.spf_colspan = rowData.spf_colspan;
			field.spf_show = $("#fieldShow_"+rowData.spf_id).val();
			field.spf_position = rowData.spf_position;
			printFields.push(field);
		}
		return printFields;
	},
	buildPrintData:function(){
		var printDatas = [];
		var ids = $("#gridData").jqGrid('getDataIDs');
		if(ids == "" || ids.length == 0){
			return printDatas;
		}
		var data = null;
		for(var i=0;i < ids.length;i++){
			var rowData = $("#gridData").jqGrid("getRowData", ids[i]);
			data = {};
			data.spd_id = rowData.spd_id;
			data.spd_code = rowData.spd_code;
			data.spd_name = rowData.spd_name;
			data.spd_namecustom = rowData.spd_namecustom;
			data.spd_width = rowData.spd_width;
			data.spd_order = rowData.spd_order;
			data.spd_show = $("#dataShow_"+rowData.spd_id).val();
			data.spd_align = $("#dataAlign_"+rowData.spd_id).val();
			printDatas.push(data);
		}
		return printDatas;
	},
	save:function(){
		var sp_id = $("#sp_id").val();
		var sp_name = $("#sp_name").val();
		if (sp_name == ''){
			Public.tips({type: 2, content : "请输入打印方案名称！"});
			$('#sp_name').focus();
			return;
		}
		var postData = {};
		postData.print = this.buildPrint();
		postData.printSets = this.buildPrintSet();
		postData.printFields = this.buildPrintField();
		postData.printDatas = this.buildPrintData();
		if(postData.printFields.length == 0){
			Public.tips({type: 2, content : "系统未配置表头设置，请联系系统管理员！"});
			return;
		}
		if(postData.printDatas.length == 0){
			Public.tips({type: 2, content : "系统未配置表格设置，请联系系统管理员！"});
			return;
		}
		var isUpdate = sp_id != "" && sp_id > 0;
		
		var saveUrl = config.BASEPATH+"sys/print/save";
		if(isUpdate){
			saveUrl = config.BASEPATH+"sys/print/update";
		}
		$("#btnSave").attr("disabled",true);
		$.ajax({
			type:"POST",
			url:saveUrl,
			data:{postData:JSON.stringify(postData)},
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					Public.tips({type: 3, content : '保存成功'});
					setTimeout("api.close()",400);
//					if(!isUpdate){
//						location.replace(location.href);
//					}
				}else{
					Public.tips({type: 1, content : data.message});
				}
				$("#btnSave").attr("disabled",false);
			}
		});
	}
};

var THISPAGE = {
	init:function(){
		this.initDom();
		this.initGridField([]);
		this.initGridData([]);
		this.initEvent();
		if(api.data.sp_id != undefined){//修改
			THISPAGE.loadPrintInfo(null,api.data.sp_id);
		}else{//新增
			THISPAGE.loadPrintInfoDefault();
		}
	},
	initDom:function(){
		
	},
	loadPrintInfo:function(obj,sp_id){
		if(obj != null){
			$(obj).siblings().removeClass();
			$(obj).addClass("thePage");
		}
		$.ajax({
			type:"POST",
			url:config.BASEPATH+'sys/print/loadPrint/'+sp_id,
			data:{},
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					THISPAGE.initPrint(data.data.print);
					THISPAGE.initGridField(data.data.fields);
					THISPAGE.initGridData(data.data.datas);
					THISPAGE.initPrintSet(data.data.sets);
				}else{
					Public.tips({type: 1, content : data.message});
				}
			}
		});
	},
	loadPrintInfoDefault:function(){
		var pt_type = $('#selectType option:selected').val();
		$.ajax({
			type:"POST",
			url:config.BASEPATH+'sys/print/loadDefaultPrint/'+pt_type,
			data:{},
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					THISPAGE.initPrint({sp_id:"",sp_name:"",sp_remark:""});
					THISPAGE.initGridField(data.data.fields);
					THISPAGE.initGridData(data.data.datas);
					THISPAGE.initPrintSet(data.data.sets);
				}else{
					Public.tips({type: 1, content : data.message});
				}
			}
		});
	},
	getSetValue:function(sets,key){
		for ( var i = 0; i < sets.length; i++) {
			var set = sets[i];
			if (set.sps_code == key){
				return set.sps_name;
			}	
		}
		return "";
	},
	initPrint:function(data){
		$("#sp_id").val(data.sp_id);
		$("#sp_name").val(data.sp_name);
		try {
			var editor = UE.getEditor('sp_remark');
			if(editor != null && editor != undefined){
				editor.sync();
				if(data.sp_remark != null){
					editor.setContent(data.sp_remark);
				}else{
					editor.setContent("");
				}
			}
		} catch (e) {
		}
	},
	initPrintSet:function(data){
		$("#page_width").val(this.getSetValue(data, "page_width"));
		$("#page_height").val(this.getSetValue(data, "page_height"));
		$("#page_left").val(this.getSetValue(data, "page_left"));
		$("#page_top").val(this.getSetValue(data, "page_top"));
		$("#page_right").val(this.getSetValue(data, "page_right"));
		$("#page_bottom").val(this.getSetValue(data, "page_bottom"));
		$("#page_title").val(this.getSetValue(data, "page_title"));
		$("#title_font").val(this.getSetValue(data, "title_font"));
		$("#title_height").val(this.getSetValue(data, "title_height"));
		$("#title_size").val(this.getSetValue(data, "title_size"));
		$("#head_font").val(this.getSetValue(data, "head_font"));
		$("#head_size").val(this.getSetValue(data, "head_size"));
		$("#page_direction").val(this.getSetValue(data, "page_direction"));
		$("input[name='page_direction'][value="+this.getSetValue(data,'page_direction')+"]").prop("checked",true);  
		$("#table_font").val(this.getSetValue(data, "table_font"));
		$("#table_size").val(this.getSetValue(data, "table_size"));
		$("#table_top").val(this.getSetValue(data, "table_top"));
		$("#table_bold").prop("checked",this.getSetValue(data, "table_bold") == "1");
		$("#table_subtotal").prop("checked",this.getSetValue(data, "table_subtotal") == "1");
		$("#table_total").prop("checked",this.getSetValue(data, "table_total") == "1");
		$("#table_headheight").val(this.getSetValue(data, "table_headheight"));
		$("#end_endshow").val(this.getSetValue(data, "end_endshow"));
		$("input[name='end_endshow'][value="+this.getSetValue(data,'end_endshow')+"]").prop("checked",true);
		$("#table_dataheight").val(this.getSetValue(data, "table_dataheight"));
		$("#head_height").val(this.getSetValue(data, "head_height"));
	},
	initGridField:function(data){
		var colModel = [
        	{name: 'spf_code',label:'字段',index: 'spf_code',hidden:true},            
	    	{name: 'spf_name',label:'名称',index: 'spf_name', width:140, title: false},
	    	{name: 'spf_namecustom',label:'显示名称',index: 'spf_namecustom', width: 140,editable:true,title: false},
	    	{name: 'spf_line',label:'行',index: 'spf_line', width: 60,editable:true,title: false},
	    	{name: 'spf_row',label:'列',index: 'spf_row', width: 80,editable:true,title: false},
	    	{name: 'spf_colspan',label:'单元格',index: 'spf_colspan', width: 60, title: false,editable:true},
	    	{name: '',label:'显示',index: 'spf_show', width: 60, align:'center',sortable:false,formatter:handle.formatFieldShow},
	    	{name: '',label:'位置',index: 'spf_position', width: 60,align:'center',sortable:false, formatter:handle.formatPosition},
	    	{name: 'spf_show',label:'',index: 'spf_show', width: 100,hidden:true},
	    	{name: 'spf_position',label:'',index: 'spf_position', width: 60,hidden:true},
	    	{name:'spf_id',hidden:true}
	    ];
		$('#grid').GridUnload();
		$('#grid').jqGrid({
			datatype: 'local',
			data:data,
			width: _width,
			height: _height,
			altRows:true,
			gridview: true,
			onselectrow: false,
			cellEdit: true,
			colModel: colModel,
			rowNum:99,
			rownumbers: true,//行号
			multiselect:false,//多选
			viewrecords: true,
			cellsubmit: 'clientArray',
			pgbuttons:true,
			shrinkToFit:false,//表格是否自动填充
			autoScroll: true,
			jsonReader: {
	            repeatitems: false,
	            id: "spf_id"
            },
			gridComplete: function(data){
				
			},
			loadError: function(xhr, status, error){		
			}
	    });
	},
	initGridData:function(data){
		var colModel = [
        	{name: 'spd_code',label:'字段称',index: 'spd_code',hidden:true},
	    	{name: 'spd_name',label:'名称',index: 'spd_name', width:100, title: false},
	    	{name: 'spd_namecustom',label:'显示名称',index: 'spd_namecustom', width: 80,editable:true,title: false},
	    	{name: '',label:'显示',index: 'spd_show', width: 60,sortable:false,formatter:handle.formatDataShow},
	    	{name: 'spd_width',label:'宽度',index: 'spd_width', width: 60, editable:true},
	    	{name: 'align',label:'对齐',index: 'align', width: 120,sortable:false,formatter:handle.formatDataAlign},
	    	{name: 'spd_order',label:'顺序',index: 'spd_order', width: 60, editable:true},
	    	{name:'spd_show',hidden:true},
	    	{name:'spd_align',hidden:true},
	    	{name:'spd_id',hidden:true}
	    ];
		$('#gridData').GridUnload();
		$('#gridData').jqGrid({
			datatype: 'local',
			data:data,
			width: _width,
			height: _height+75,
			altRows:true,
			gridview: true,
			onselectrow: false,
			cellEdit: true,
			colModel: colModel,
			rowNum:99,
			rownumbers: true,//行号
			viewrecords: true,
			cellsubmit: 'clientArray',
			pgbuttons:true,
			shrinkToFit:false,//表格是否自动填充
			autoScroll: true,
			jsonReader: {
	            repeatitems: false,
	            id: "spd_id"
            },
            gridComplete: function(data){
				
			},
			loadError: function(xhr, status, error){		
			}
	    });
	},
	initEvent:function(){
		$('#btnAdd').on('click',function(){
			$(this).siblings().removeClass();
			THISPAGE.loadPrintInfoDefault();
		});
		$('#btnSave').on('click',function(){
			handle.save();
		});
		$("#btn_close").click(function(e){
			e.preventDefault();
			api.close();
		});
	}
};

THISPAGE.init();